#include "triggerstab.h"


TriggersTab::TriggersTab(AED_Archtype* arch, ScriptModel *scriptm, QWidget *parent ) :
    QWidget(parent),m_arch(arch)
{
    m_scriptmodel = new TriggerScriptModel(arch,scriptm);

    m_parentscriptmodel = scriptm;

    m_conditionmodel = new TriggerConditionModel(0);
    QVBoxLayout *main_layout = new QVBoxLayout();

    this->setLayout(main_layout);

    QVBoxLayout *scriptlayout = new QVBoxLayout();

    m_scriptview = new QListView();
    m_scriptview->setModel(m_scriptmodel);
    m_delegate = new ComboBoxDelegate();
    m_scriptview->setItemDelegate(m_delegate);
    PopulateScripts();

    QHBoxLayout *bbox1 = new QHBoxLayout;
    m_addtrigger = new QPushButton("Add Trigger");
    m_removetrigger = new QPushButton("Remove Trigger");
    QPushButton *loadscript = new QPushButton("Load Script");

    m_warnbox = new QHBoxLayout;
    m_warning = new QLabel("You have to load a script to set up a trigger!");
    m_warnbox->addWidget(m_warning);

    bbox1->addWidget(m_addtrigger);
    bbox1->addWidget(m_removetrigger);
    bbox1->addWidget(loadscript);
    scriptlayout->addLayout(bbox1);
    scriptlayout->addLayout(m_warnbox);

    CheckScripts();

    scriptlayout->addWidget(m_scriptview);


    QVBoxLayout *condlayout = new QVBoxLayout();

    m_condview = new QTableView();
    m_condview->setModel(m_conditionmodel);
    m_condview->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_condview->setSelectionMode(QAbstractItemView::SingleSelection);
    m_condview->horizontalHeader()->setResizeMode(QHeaderView::Stretch);


    QHBoxLayout *condbox = new QHBoxLayout;
    typebox = new QComboBox;
    namebox = new QComboBox;
    condbox->addWidget(typebox);
    condbox->addWidget(namebox);

    QHBoxLayout *bbox2 = new QHBoxLayout;
    QPushButton *addcond = new QPushButton("Add Condition");
    QPushButton *removecond = new QPushButton("Remove Condition");
    bbox2->addWidget(addcond);
    bbox2->addWidget(removecond);


    condlayout->addLayout(condbox);
    condlayout->addLayout(bbox2);
    condlayout->addWidget(m_condview);

    main_layout->addLayout(scriptlayout);
    main_layout->addLayout(condlayout);

    setArchtype(arch);


    /*connect(m_scriptview->selectionModel(),SIGNAL(currentChanged(QModelIndex,QModelIndex)),
            this,SLOT(UpdateConditions(QModelIndex,QModelIndex)));*/
    connect(m_scriptview,SIGNAL(clicked(QModelIndex)),
            this,SLOT(UpdateConditions(QModelIndex)));
    connect(m_addtrigger,SIGNAL(pressed()),m_scriptmodel,SLOT(AddScript()));
    connect(m_removetrigger,SIGNAL(pressed()),this,SLOT(RemoveTrigger()));
    connect(loadscript,SIGNAL(pressed()),this,SLOT(LoadScript()));
    connect(addcond,SIGNAL(pressed()),this,SLOT(AddCondition()));
    connect(removecond,SIGNAL(pressed()),this,SLOT(RemoveCondition()));
    connect(typebox,SIGNAL(activated(QString)),this,SLOT(UpdateNames(QString)));
    connect(m_parentscriptmodel, SIGNAL(modified()),this,SLOT(PopulateScripts()));
    connect(m_parentscriptmodel, SIGNAL(modified()),this,SLOT(CheckScripts()));

}

void TriggersTab::setArchtype(AED_Archtype* arch){
    m_arch = arch;
    if(m_arch){
        this->setEnabled(true);
        m_scriptmodel->setArchtype(arch);
        this->UpdateTypes(0);
        PopulateScripts();
        CheckScripts();
        m_scriptview->clearSelection();
        m_conditionmodel->Update(0);
    }else{
        m_scriptmodel->setArchtype(0);
        m_scriptview->clearSelection();
        m_conditionmodel->Update(0);
        this->setEnabled(false);
    }
}


void TriggersTab::UpdateTypes(int tab){
    typebox->clear();

    if(m_arch->GetAlwaysComp()->IsEnabled()){
        typebox->addItem("Always");
        //UpdateNames("Always");
    }
    if(m_arch->GetKeyboardComp()->IsEnabled()){
        typebox->addItem("Keyboard");
        //UpdateNames("Keyboard");
    }
    if(m_arch->GetMouseComp()->IsEnabled()){
        typebox->addItem("Mouse");
        //UpdateNames("Mouse");
    }
    if(m_arch->GetPhysicsComp()->IsEnabled()){
        typebox->addItem("Physics");
        //UpdateNames("Physics");
    }
    UpdateNames(typebox->currentText());
}

void TriggersTab::UpdateNames(const QString &type){
    namebox->clear();
    if(type=="Always"){
        QList<AED_AlwaysComp::Condition>* list = m_arch->GetAlwaysComp()->GetConditionList();
        for(int i=0;i<list->size();i++){
            namebox->addItem((*list)[i].name);
        }
    }else if(type=="Keyboard"){
        QList<AED_KeyboardComp::Condition>* list = m_arch->GetKeyboardComp()->GetConditionList();
        for(int i=0;i<list->size();i++){
            namebox->addItem((*list)[i].name);
        }
    }else if(type=="Mouse"){
        QList<AED_MouseComp::Condition>* list = m_arch->GetMouseComp()->GetConditionList();
        for(int i=0;i<list->size();i++){
            namebox->addItem((*list)[i].name);
        }
    }else if(type=="Physics"){
        QList<AED_PhysicsComp::Condition>* list = m_arch->GetPhysicsComp()->GetConditionList();
        for(int i=0;i<list->size();i++){
            namebox->addItem((*list)[i].name);
        }
    }
}

void TriggersTab::UpdateConditions(QModelIndex index, QModelIndex unused){
    Q_UNUSED(unused);
    int row = index.row();
    qDebug() << "Row: "<< row;
    AED_Trigger* trig = &m_arch->GetTriggers()->operator [](row);
    m_conditionmodel->Update(trig);
}

void TriggersTab::UpdateConditions(QModelIndex index){
    int row = index.row();
    qDebug() << "Row: "<< row;
    AED_Trigger* trig = &m_arch->GetTriggers()->operator [](row);
    m_conditionmodel->Update(trig);
}

void TriggersTab::RemoveTrigger(){
    QModelIndexList lstIndex ;

    QItemSelection ranges = m_scriptview->selectionModel()->selection();
    for (int i = 0; i < ranges.count(); ++i){
        QModelIndex parent = ranges.at(i).parent();
        int right = ranges.at(i).model()->columnCount(parent) - 1;
        if (ranges.at(i).left() == 0 && ranges.at(i).right() == right)
            for (int r = ranges.at(i).top(); r <= ranges.at(i).bottom(); ++r)
                lstIndex.append(ranges.at(i).model()->index(r, 0, parent));
    }
    for(int i=0; i<lstIndex.size();i++){
        QModelIndex index = lstIndex.at(i);
        if(index.isValid()){
            m_scriptmodel->RemoveScript(index.row());
            m_conditionmodel->Update(0);
            m_scriptview->selectionModel()->clearSelection();
        }
    }
}

void TriggersTab::AddCondition(){
    QString type = typebox->currentText();
    QString name = namebox->currentText();
    if(!type.isEmpty()&&!name.isEmpty())
        m_conditionmodel->AddCondition(type,name);
}

void TriggersTab::RemoveCondition(){
    QModelIndexList lstIndex ;

    QItemSelection ranges = m_condview->selectionModel()->selection();
    for (int i = 0; i < ranges.count(); ++i){
        QModelIndex parent = ranges.at(i).parent();
        int right = ranges.at(i).model()->columnCount(parent) - 1;
        if (ranges.at(i).left() == 0 && ranges.at(i).right() == right)
            for (int r = ranges.at(i).top(); r <= ranges.at(i).bottom(); ++r)
                lstIndex.append(ranges.at(i).model()->index(r, 0, parent));
    }

    for(int i=0; i<lstIndex.size();i++){
        QModelIndex index = lstIndex.at(i);
        if(index.isValid()){
             m_conditionmodel->RemoveCondition(index.row());
        }
    }

}

void TriggersTab::LoadScript(){
    QString fileName = QFileDialog::getOpenFileName(this,
         tr("Open Image"), "/home/", tr("Python Files (*.py)"));

    if(!fileName.isNull())
        m_parentscriptmodel->LoadScript(fileName);

    PopulateScripts();
    CheckScripts();
}

void TriggersTab::CheckScripts(){
    if(m_parentscriptmodel->rowCount()==0){
        m_addtrigger->setEnabled(false);
        m_removetrigger->setEnabled(false);
        m_warning->setVisible(true);
    }else{
        m_addtrigger->setEnabled(true);
        m_removetrigger->setEnabled(true);
        m_warning->setVisible(false);
    }
}

void TriggersTab::PopulateScripts(){
    m_delegate->Clear();
    for(int i=0;i<m_parentscriptmodel->rowCount();i++){
        m_delegate->AddItem(m_parentscriptmodel->GetScript(i)->GetPath());
    }
}
